<?php
namespace cms\modules\v1\models\shop;

use common\models\Functions;
use common\models\Status;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use Yii;
/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class Goods extends \common\models\shop\Goods
{

    public $category;

    public function rules()
    {
        return [
            [['content','category_id','deputy_image','num','sale_nums','price','comment_nums','collect_nums','like_nums','type','status','old_price'],'required','message' => "{attribute}不能为空", 'on' => ['addEdit']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'name' => '名称',
            'content' => '详情',
            'category_id' => '分类',
            'deputy_image' => '商品副图',
            'price' => '价格',
            'old_price' => '原价',
            'comment_nums' => '评论数量',
            'num' => '库存',
            'sale_nums' => '销量',
            'collect_nums' => '收藏数量',
            'like_nums' => '想要数量',
            'type' => '类型',
            'status' => '状态',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios()
    {
        $scenarios = [
            'addEdit' => [
                'name',
                'content',
                'category_id',
                'deputy_image',
                'price',
                'num',
                'sale_nums',
                'old_price',
                'comment_nums',
                'collect_nums',
                'like_nums',
                'type',
                'status',
            ],
        ];
        return array_merge(parent::scenarios(), $scenarios);
    }

    /**
     * 返回列表数据
     * @param int $page
     * @param int $size
     * @return array
     */
    public function getListData($page = 1, $size = 20) {
        try {

            //搜索条件
            $searchWhere  = $this->getSearch();//自定义搜索条件

            //得到文章的总数
            $count = static::getObjectCountByAndWhere($searchWhere['where'], $searchWhere['andWhere'])->count();

            $data = static::setPageinationAPI($page, $size, $count);

            $returnData = [
                'total' => (int ) $count,
                'page' => (int) $page,
                'totalPage' => (int) $data['totalPage'],
                "data" => null
            ];

            //设置分页
            $offset = ($page - 1) * $size;

            //排序 order
            $orderSql = 'id DESC';

            $query = static::getObjectByAndWhere($searchWhere['where'], $searchWhere['andWhere'], '*', $orderSql, $offset, $size);

            $returnData['data'] = $this->handelList($query);

            return Functions::formatRestAPI(0, '', $returnData);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 自定义参数的搜索  搜索,搜索也分每一列
     * 这里要根据业务逻辑进行修改
     * @return string
     */
    public function getSearch () {
        $where['is_delete'] = Status::COMMON_STATUS_SHOW;
        $andWhere = [];
        $category = Yii::$app->request->get('category','');
        $status = Yii::$app->request->get('status','');
        $Name = Yii::$app->request->get('name','');
        $type = Yii::$app->request->get('type','');
//        $is_sell = Yii::$app->request->get('is_sell','');
        $check_status = Yii::$app->request->get('check_status','');
        $loginName = Yii::$app->request->get('login_name','');

        if($category) {
            $where['category_id'] = $category;
        }
        if ($type) {
            $where['type'] = (int) $type;
        }
//        if ($is_sell) {
//            $where['is_sell'] = (int) $is_sell;
//        }
        if ($check_status) {
            $where['check_status'] = (int) $check_status;
        }
        if ($status) {
            $where['status'] = (int) $status;
        }
        if ($Name) {
            $andWhere[] = ['like','name',$Name];
        }

        if ($loginName) {
            $ids = \common\models\user\User::searchByName($loginName);
            $where['user_id'] = $ids;
        }
        return [
            'where' => $where,
            'andWhere' => $andWhere
        ];
    }

    /**
     * 处理初始化数据
     * @param $query
     * @return mixed
     */
    public function handelList($query = null) {
        if (empty($query)) {
            return null;
        }
        $list = $query->with(['category','user'])
            ->asArray()->all();

        foreach ($list as &$v) {
            $v['images'] = static::getImages($v['images']);
            $imageTmp = [];
            $imageArray = $v['deputy_image'] ? json_decode($v['deputy_image'],true) : [];
            if ($imageArray) {
                foreach ($imageArray as $vv) {
                    $imageTmp[] = static::getImages($vv);
                }
            }
            $v['deputy'] = $imageTmp ?? '';
        }
        return $list;
    }

    public function getInfo($id = 0) {
        try {
            if (empty($id)) {
                throw new Exception('未知信息');
            }

            $info = static::getOneInfoById($id);
            if (empty($info)) {
                throw new Exception('未知信息');
            }

//            $imageArray = [];
//            if ($info['deputy_image']) {
//                $imageArray = json_decode($info['deputy_image'],true);
//                foreach ($imageArray as $k=>$v) {
//                    $imageArray[$k] = [
//                        'url'=>static::getImages($v),
//                        'path'=>$v,
//                    ];
//                }
//            }


            $info['deputy_image'] = static::getAllImagesWithType($info['deputy_image']);

            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 添加修改
     * @return array
     */
    public function addEdit() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            $id = Yii::$app->request->post('id',0);
            $post = Yii::$app->request->post();
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));

            $deputyImage = Yii::$app->request->post('deputy_image',[]);

            if(empty($deputyImage)){
                throw new Exception('请上传多图');
            }

            //如果有多图上传 后上传
            $deputyImageArr = json_decode($deputyImage,true);
            foreach($deputyImageArr as $v){
                $images[] = $v['path'];
            }
            $imageTmp = json_encode($images);
            $data['deputy_image'] = $imageTmp;

            if($data['type'] == Status::GOODS_TYPE_NAME_OFFICIAL){
                $data['check_status'] = Status::COMMON_CHECKING_SUCCESS;
            }

            if (!empty($id)) {
                //更新操作
                $data['update_time'] = date('Y-m-d H:i:s');

                $res = static::updateDataWithLog($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception('更新失败');
                }
            } else {
                throw new Exception('请使用APP进行商品的发布');
                //添加操作
                $data['update_time'] = $data['create_time'] = date('Y-m-d H:i:s');

                $res = static::insertDataWithLog($data);
                if ($res === false) {
                    throw new Exception('添加失败');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function deleteGoods($id = 0) {
        try {

            $id = Yii::$app->request->post('id', $id);

            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $data['is_delete'] = Status::COMMON_STATUS_HIDDEN;

            $res = static::updateData($data, ['id' => $id]);

            if ($res == false) {
                throw new Exception('删除失败');
            }
            return Functions::formatRestAPI(0, '删除成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getMapForSelect() {
        $list = static::getByWhere();

        $result = [];
        foreach ($list as $v) {
            $result[] = [
                "id" => $v['id'],
                'name' => $v['name']
            ];
        }

        return Functions::formatRestAPI(0, '', $result);
    }

    /**
     * 商品审核
     * @return array
     * @throws \yii\db\Exception
     */
    public function examineInfo() {
        $trans = Yii::$app->db->beginTransaction();
        try{
            $id = Yii::$app->request->post('id','');
            $check_status = Yii::$app->request->post('check_status','');
            $reason = Yii::$app->request->post('reason','');
            if (empty($id)|| empty($check_status)){
                throw new Exception('缺少参数');
            }

            if (!is_array($id)) {
                $ids = [$id];
            } else {
                $ids = $id;
            }

            if($check_status == Status::COMMON_CHECKING_DEFEAT) {
                if (empty($reason)){
                    throw new Exception('请填写驳回理由');
                }
                $data['reason'] = $reason;
            }

            foreach ($ids as $v) {
                $data['check_status'] = $check_status;
                $data['update_time'] = date('Y-m-d H:i:s');
                $res = static::updateData($data, ['id' => $v]);

                if ($res === false){
                    throw new Exception('操作失败');
                }
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
